package com.yc.fav.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yc.fav.Utils;
import com.yc.fav.entity.Fav;
import com.yc.fav.entity.Tag;
import com.yc.fav.entity.TagFav;
import com.yc.fav.entity.User;
import com.yc.fav.mapper.FavMapper;
import com.yc.fav.mapper.TagFavMapper;
import com.yc.fav.mapper.TagMapper;
import com.yc.fav.vo.Result;
import org.springframework.context.ApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Company 源辰信息
 *
 * @author navy
 * @date 2024/8/6
 * Email haijunzhou@hnit.edu.cn
 */
@WebServlet("/queryTagFav")
public class QueryTagFavServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ApplicationContext cxt = (ApplicationContext) this.getServletContext().getAttribute("cxt");
        Result result=new Result();
        FavMapper favMapper = cxt.getBean(FavMapper.class);
        TagMapper tagMapper = cxt.getBean(TagMapper.class);
        TagFavMapper tagFavMapper = cxt.getBean(TagFavMapper.class);

                if(req.getSession().getAttribute("loginedUser")==null){
            result.setCode(0);
            result.setMsg("请先登录系统");
            Utils.print(resp,result);
            return;
        }
        User user = (User) req.getSession().getAttribute("loginedUser");

        // TODO 完成登录功能之后, 请回复这里的代码
      /*  User user = new User();
        user.setId(1);*/

        Integer uid = user.getId();
        LambdaQueryWrapper<Fav> lqw1 = new LambdaQueryWrapper<>();
        lqw1.eq(Fav::getUid, uid);
        List<Fav> favs = favMapper.selectList(lqw1);

        LambdaQueryWrapper<Tag> lqw2 = new LambdaQueryWrapper<>();
        lqw2.eq(Tag::getUid, uid);
        List<Tag> tags = tagMapper.selectList(lqw2);

        //服务器异常处理
        List<TagFav> tagFavs = null;
        if(tags != null && !tags.isEmpty()){
        LambdaQueryWrapper<TagFav> lqw3 = new LambdaQueryWrapper<>();
        lqw3.in(TagFav::getTid, tags.stream()
                                    .map(tag->tag.getId())
                                    .collect(Collectors.toList()));
        tagFavs = tagFavMapper.selectList(lqw3);
        }

        Map<String,Object> data = new HashMap<>();
        data.put("favs", favs);
        data.put("tags", tags);
        data.put("tagFavs", tagFavs);

        Utils.print(resp, data);

    }
}
